
package com.shiku.utils.encrypt;


import com.shiku.utils.Base64;

import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AES {
    private static byte[] iv = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};


    public static byte[] encrypt(byte[] content, byte[] password) {

        try {

            if (password.length != 16) {

                password = Arrays.copyOfRange(password, 0, 16);

            }

            KeyGenerator kgen = KeyGenerator.getInstance("AES");

            SecretKeySpec key = new SecretKeySpec(password, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            cipher.init(1, key, new IvParameterSpec(iv));

            return cipher.doFinal(content);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }


    public static String encryptBase64(byte[] content, byte[] password) {

        return Base64.encode(encrypt(content, password));

    }


    public static String encryptBase64(String content, byte[] password) {

        return Base64.encode(encrypt(content.getBytes(), password));

    }


    public static byte[] decrypt(byte[] content, byte[] password) {

        try {

            if (password.length != 16) {

                password = Arrays.copyOfRange(password, 0, 16);

            }

            KeyGenerator kgen = KeyGenerator.getInstance("AES");

            SecretKeySpec key = new SecretKeySpec(password, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            cipher.init(2, key, new IvParameterSpec(iv));

            return cipher.doFinal(content);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }


    public static byte[] decryptFromBase64(String content, byte[] password) {

        return decrypt(Base64.decode(content), password);

    }


    public static String decryptString(byte[] content, byte[] password) {

        return new String(decrypt(content, password));

    }


    public static String decryptStringFromBase64(String content, byte[] password) {

        return new String(decrypt(Base64.decode(content), password));

    }

}


